package com.tzbank.wisdom.service.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.sunyard.client.SunEcmClientApi;
import com.sunyard.client.bean.ClientBatchBean;
import com.sunyard.client.bean.ClientBatchFileBean;
import com.sunyard.client.bean.ClientBatchIndexBean;
import com.sunyard.client.bean.ClientFileBean;
import com.sunyard.client.impl.SunEcmClientSocketApiImpl;
import com.tzbank.utils.ResultCode;
import com.tzbank.utils.ResultUtil;
import com.tzbank.wisdom.service.UploadService;
import com.tzbank.wisdom.utils.FileUploadUtil;

import lombok.extern.slf4j.Slf4j;



@Service(value = "UploadService")
@Slf4j
public class UploadServiceImpl implements UploadService {
	
	@Value("${videoPlatform.ip}")
	String ip; //为SunECMDM的ip地址
	@Value("${videoPlatform.socketPort}")
	String socketPort; //为SunECMDM的socket端口
	@Value("${videoPlatform.groupName}")
	String groupName; // 内容存储服务器组名
	@Value("${videoPlatform.modelCode}")
	String modelCode; // 索引对象内容模型代码
	@Value("${videoPlatform.filePartName}")
	String filePartName;  // 文档对象模型代码
	@Value("${videoPlatform.userName}")
	String userName; //登录SunECMDM的用户名
	@Value("${videoPlatform.passWord}")
	String passWord; //登录SunECMDM的密码
	@Value("${videoPlatform.STARTCOLUMN}")
	String STARTCOLUMN; //业务开始时间的属性英文名称
	@Value("${videoPlatform.token_check_value}")
	String token_check_value; //设置令牌校验值（自定义）
	@Value("${videoPlatform.tokenIP}")
	String tokenIP; //获取令牌号http地址
	
	@Value("${videoPlatform.picPath}")
	String pt; //获取令牌号http地址
	
	
	String STARTDATE = new SimpleDateFormat("yyyyMMdd").format(new Date());; //业务开始时间的值	
	
	static int gainContent_id=1;//解析xml获取content_id 操作码
	static int gainAmount=0;//解析xml获取amount 操作码

	
	
	
	
	/**
	 * function 上传操作
	 * @return String
	 * @throws Exception
	 * identityCode :身份证正面101903 ；身份证反面：101904；
	 * busino 流水号（YDYYT） 开头以平台名字命名
	 */
	@Override
	public Map<String, Object> upload(String identityCode , String files, String busino) {
		SunEcmClientApi clientApi = new SunEcmClientSocketApiImpl(ip, Integer.valueOf(socketPort));  
		  //  String path=uploadFile(files,pt);
		    String path="";
		    Map<String, String> mapPic = new HashMap<String, String>();
		    try {
		    	mapPic=FileUploadUtil.upload(files, pt);
		    	path =mapPic.get("localFile");
			} catch (Exception e) {
				log.error("上传到智脑服务器异常:",e);
				return   ResultUtil.resultMap(ResultCode.RESUTL_CODE_FAILURE.desc(),ResultCode.RESUTL_CODE_FAILURE.code(),e.getMessage());
			}
		    
		    Map<String, String> map= new HashMap<String, String>();
		    map.put(identityCode, path);
			String resultMsg="";
			ClientBatchBean clientBatchBean = new ClientBatchBean(); // 创建批次对象
			clientBatchBean.setModelCode(modelCode); // 设置元数据索引对象内容模型 GlobalVar.IndexTable
			clientBatchBean.setUser(userName); 
			clientBatchBean.setPassWord(passWord);
			clientBatchBean.setBreakPoint(false); // 是否作为断点续传上传
			// 若内容模型配置有安全校验,则放开下面代码
//			clientBatchBean.setToken_check_value(token_check_value);
//			clientBatchBean.setToken_code(this.getToken());
			
			// =========================设置索引对象信息开始=========================
			ClientBatchIndexBean clientBatchIndexBean = new ClientBatchIndexBean();
			clientBatchIndexBean.addCustomMap("BUSI_SERIAL_NO", busino);
			clientBatchIndexBean.addCustomMap(STARTCOLUMN, STARTDATE);
			clientBatchIndexBean.addCustomMap("AMOUNT", "1");
			// =========================设置索引对象信息结束=========================
			
			// =========================设置文档部件信息开始=========================
			ClientBatchFileBean clientBatchFileBean = new ClientBatchFileBean();
			clientBatchFileBean.setFilePartName(filePartName);
			// =========================设置文档部件信息结束=========================
			
			ClientFileBean fileBean= new ClientFileBean();
			Map<String,String> fileMap=getMap(map);//获取Map中的值
			setProperty(fileBean , fileMap);//添加文件信息
			clientBatchFileBean.addFile(fileBean);// 将文件加入到文档部件中
			
			clientBatchBean.setIndex_Object(clientBatchIndexBean);
			clientBatchBean.addDocument_Object(clientBatchFileBean);
			try {
				resultMsg = clientApi.upload(clientBatchBean, groupName);
				//System.out.println("#######上传批次返回的信息[" + resultMsg + "]#######");
			} catch (Exception e) {
				//删除存在智脑服务器上的图片
				deletePic(path);
				log.error("上传批次出现异常，批次号为："+clientBatchBean.getIndex_Object().getContentID() , e);
				return ResultUtil.resultMap(ResultCode.RESUTL_CODE_FAILURE.desc(),ResultCode.RESUTL_CODE_FAILURE.code(),e.getMessage());
			}
			//删除存在智脑服务器上的图片
			deletePic(path);
			
			if(resultMsg.contains("SUCCESS")) {
				log.info("响应:",resultMsg);
				return ResultUtil.resultMap(ResultCode.RESULT_CODE_SUCCESS.desc(), ResultCode.RESULT_CODE_SUCCESS.code(),resultMsg );
			}else {
				log.error("上传到影像平台异常:",resultMsg);
				return ResultUtil.resultMap(ResultCode.RESUTL_CODE_FAILURE.desc(), ResultCode.RESUTL_CODE_FAILURE.code(),resultMsg );
			}
		
	}
	
	/**
	 * function 解析Map
	 * @param map
	 * @return listFile
	 */
	private Map<String,String> getMap(Map<String,String> map){
		Map<String,String> fileMap=new HashMap<String,String>();
		String busi_file_type="";
		String filePath="";
		String fileFormat="";
		for(String key:map.keySet()){
			busi_file_type=key;
			filePath=map.get(key);
			File f = new File(filePath);
			
			String[] strs=filePath.split("\\.");
			fileFormat=strs[1];
			fileMap.put("busi_file_type", busi_file_type);
			fileMap.put("filePath", filePath);
			fileMap.put("fileFormat", f.getName().substring(f.getName().lastIndexOf(".")+1));
		}
		return fileMap;	
	}

	/**
	 * function 添加文件
	 * @param fileBean
	 * @param pageNum
	 * @param fileMap
	 */
	private void setProperty(ClientFileBean fileBean, Map<String,String> fileMap){
		fileBean.setFileName(fileMap.get("filePath"));//文件路径
		fileBean.setFileFormat(fileMap.get("fileFormat"));//文件格式
		fileBean.addOtherAtt("BUSI_FILE_TYPE",fileMap.get("busi_file_type"));//影像节点
		fileBean.addOtherAtt("EXPIRE_DATE", "9999-12-31");	//文件有效期
	}
	
	
	/**
	 * function 删除存在智脑服务器的图片
	 * @param absolutePath  绝对路径
	 * 
	 * 
	 */
	public void deletePic(String absolutePath){
		File  file= new File(absolutePath);
		if(file.exists()) {
			file.delete();
		}
	}
	
	
	
	
	/**
	 * function 批量上传图片到 mpath
	 *@param  identityCode :身份证正面101903 ；身份证反面：101904；
	 *@param busino 流水号（YDYYT） 开头以平台名字命名
	 * @return
	 */

	public Map<String, Object> uploadList(String identityFront ,String busino,String identityOpposite ) {
		Map<String,String> map  =new  HashMap<String,String>();
		map.put("101903", identityFront);
		map.put("101904", identityOpposite);
		
		SunEcmClientApi clientApi = new SunEcmClientSocketApiImpl(ip, Integer.valueOf(socketPort)); 
		    
		 
		    
		  List<Map<String,String>> listMap = new ArrayList<Map<String,String>>() ;   
		   List<String> pathList =new ArrayList<String>();
		for(Map.Entry<String,String> entry :map.entrySet()) {
			String m=entry.getValue();
			String path="";
			Map<String,String> mapPic =new  HashMap<String,String>();
		    try {
		    	mapPic=FileUploadUtil.upload(m, pt);
		    	path=mapPic.get("localFile");
			} catch (Exception e) {
				
				log.error("上传到智脑服务器异常:",e);
				return   ResultUtil.resultMap(ResultCode.RESUTL_CODE_FAILURE.desc(),ResultCode.RESUTL_CODE_FAILURE.code(),e.getMessage());
			} 
		    
		    Map<String, String> mapOne= new HashMap<String, String>();
		    mapOne.put(entry.getKey(), path);  
		    pathList.add(path);
		    listMap.add(mapOne);
		}
		
		String resultMsg="";
		ClientBatchBean clientBatchBean = new ClientBatchBean(); // 创建批次对象
		clientBatchBean.setModelCode(modelCode); // 设置元数据索引对象内容模型 GlobalVar.IndexTable
		clientBatchBean.setUser(userName); 
		clientBatchBean.setPassWord(passWord);
		clientBatchBean.setBreakPoint(false); // 是否作为断点续传上传
		// 若内容模型配置有安全校验,则放开下面代码
//		clientBatchBean.setToken_check_value(token_check_value);
//		clientBatchBean.setToken_code(this.getToken());
		
		// =========================设置索引对象信息开始=========================
		ClientBatchIndexBean clientBatchIndexBean = new ClientBatchIndexBean();
		clientBatchIndexBean.addCustomMap("BUSI_SERIAL_NO", busino);
		clientBatchIndexBean.addCustomMap(STARTCOLUMN, STARTDATE);
		clientBatchIndexBean.addCustomMap("AMOUNT", String.valueOf(listMap.size()));
		// =========================设置索引对象信息结束=========================
		
		// =========================设置文档部件信息开始=========================
		ClientBatchFileBean clientBatchFileBean = new ClientBatchFileBean();
		clientBatchFileBean.setFilePartName(filePartName);
		// =========================设置文档部件信息结束=========================
		
		ClientFileBean fileBean=null;
		for(int i=0;i<listMap.size();i++){
			fileBean = new ClientFileBean();
			Map<String,String> amap= listMap.get(i);
			Map<String,String> fileMap=getMap(amap);//获取Map中的值
			setProperty(fileBean , fileMap);//添加文件信息
			clientBatchFileBean.addFile(fileBean);// 将文件加入到文档部件中
		}
		clientBatchBean.setIndex_Object(clientBatchIndexBean);
		clientBatchBean.addDocument_Object(clientBatchFileBean);
		try {
			resultMsg = clientApi.upload(clientBatchBean, groupName);
			log.info("响应"+resultMsg);
			//System.out.println(resultMsg);
//			System.out.println("#######上传批次返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			log.error("上传批次出现异常，批次号为："+clientBatchBean.getIndex_Object().getContentID() , e);
			//删除存在智脑服务器上的图片
			for(String p :pathList) {
				deletePic(p);
			}
			
			return ResultUtil.resultMap(ResultCode.RESUTL_CODE_FAILURE.desc(),ResultCode.RESUTL_CODE_FAILURE.code(),null);
		}
		//删除存在智脑服务器上的图片
		for(String p :pathList) {
			deletePic(p);
		}
		return ResultUtil.resultMap(ResultCode.RESULT_CODE_SUCCESS.desc(), ResultCode.RESULT_CODE_SUCCESS.code(),resultMsg );
			
	}
	
	

	
	
	
	
}